/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import pojo.*;

/**
 *
 * @author DQ
 */
public class ThongTinKeyDAO {

    public static String layDuongDanTapTin() {
        return "KeyStore/ThongTinKey.xml";
    }

    public static ArrayList<ThongTinKey> layTatCaThongTinKey() {
        ArrayList<ThongTinKey> arrKey = new ArrayList<>();

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(layDuongDanTapTin());

            Element root = doc.getDocumentElement();
            NodeList list = root.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                if (node instanceof Element) {
                    Element element = (Element) node;
                    ThongTinKey ttk = new ThongTinKey();
                    ttk.setMaKey(Integer.parseInt(element.getAttribute("MaKey")));

                    NodeList elist = element.getChildNodes();
                    for (int j = 0; j < elist.getLength(); j++) {
                        Node enode = elist.item(j);
                        if (enode instanceof Element) {
                            Element ele = (Element) enode;
                            Text textNode = (Text) ele.getFirstChild();
                            String content = textNode.getData();
                            switch (ele.getTagName()) {
                                case "LoaiKey":
                                    ttk.setLoaiKey(content);
                                    break;
                                case "DiaChiMail":
                                    ttk.setDiaChiMail(content);
                                    break;
                                case "DuongDan":
                                    ttk.setDuongDan(content);
                                    break;

                            }
                        }
                    }
                    //Add key vao list
                    arrKey.add(ttk);
                }

            }
        } catch (Exception e) {
        }
        return arrKey;

    }

    public static void capNhatThongTinKey(ThongTinKey key) throws TransformerConfigurationException, TransformerException, ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(layDuongDanTapTin());
        Element root = doc.getDocumentElement();
        NodeList list = root.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;

                if (Integer.parseInt(element.getAttribute("MaKey")) == key.getMaKey()) {
                    NodeList elist = element.getChildNodes();
                    for (int j = 0; j < elist.getLength(); j++) {
                        Node enode = elist.item(j);
                        if (enode instanceof Element) {
                            Element ele = (Element) enode;
                            Text textNode = (Text) ele.getFirstChild();
                            String content = textNode.getData();
                            switch (ele.getTagName()) {
                                case "LoaiKey":
                                    ele.setTextContent(key.getLoaiKey());
                                    break;
                                case "DiaChiMail":
                                    ele.setTextContent(key.getDiaChiMail());
                                    break;
                                case "DuongDan":
                                    ele.setTextContent(key.getDuongDan());
                                    break;

                            }
                        }
                    }

                }
            }

        }
        //Ghi file
        ghiFile(doc);
    }

    public static void xoaThongTinKey(ThongTinKey key) throws TransformerConfigurationException, TransformerException, ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(layDuongDanTapTin());
        Element root = doc.getDocumentElement();
        NodeList list = root.getChildNodes();
        for (int i = list.getLength()-1; i >=0; i--) {
            Node node = list.item(i);
            
            if (node instanceof Element) {
                Element element = (Element) node;

                if (Integer.parseInt(element.getAttribute("MaKey")) == key.getMaKey()) {

                   Node nodePra = list.item(i).getParentNode();
                   nodePra.removeChild(list.item(i));
                   ghiFile(doc);
                   return;
                }
            }

        }
        //Ghi file
        //ghiFile(doc);
        
    }

    public static ThongTinKey timKiemPrivateKey(String diaChiEmail) {

        ArrayList<ThongTinKey> arrTTK = new ArrayList<>();
        try {
            arrTTK = layTatCaThongTinKey();
            for (int i = 0; i < arrTTK.size(); i++) {
                ThongTinKey ttk = arrTTK.get(i);

                if (ttk.getDiaChiMail().equals(diaChiEmail) == true && ttk.getLoaiKey().equals("Private") == true) {

                    return ttk;


                }
            }
        } catch (Exception e) {
        }

        return null;
    }

    public static ThongTinKey timKiemPublicKey(String diaChiEmail) {

        ArrayList<ThongTinKey> arrTTK = new ArrayList<>();
        try {
            arrTTK = layTatCaThongTinKey();
            for (int i = 0; i < arrTTK.size(); i++) {
                ThongTinKey ttk = arrTTK.get(i);

                if (ttk.getDiaChiMail().equals(diaChiEmail) == true && ttk.getLoaiKey().equals("Public") == true) {

                    return ttk;


                }
            }
        } catch (Exception e) {
            return null;
        }

        return null;
    }

    public static ThongTinKey timKiemPreSharedKey(String diaChiEmail) {

        ArrayList<ThongTinKey> arrTTK = new ArrayList<>();
        try {
            arrTTK = layTatCaThongTinKey();
            for (int i = 0; i < arrTTK.size(); i++) {
                ThongTinKey ttk = arrTTK.get(i);

                if (ttk.getDiaChiMail().equals(diaChiEmail) == true && ttk.getLoaiKey().equals("PreShared") == true) {

                    return ttk;


                }
            }
        } catch (Exception e) {
        }

        return null;
    }
    
    private static void ghiFile(Document doc) throws TransformerConfigurationException, TransformerException {

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(layDuongDanTapTin());

        transformer.transform(source, result);

    }

    public static int layMaKeyTuFile() {

        int maKey = 0;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(layDuongDanTapTin());
            Element root = doc.getDocumentElement();
            NodeList list = root.getChildNodes();
            maKey = list.getLength();

        } catch (ParserConfigurationException | SAXException | IOException ex) {
        }
        return maKey;

    }

    public static void themKeyMoi(ThongTinKey ttk) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(layDuongDanTapTin());

            Element root = doc.getDocumentElement();
            Element key = doc.createElement("Key");
            key.setAttribute("MaKey", Integer.toString(ttk.getMaKey()));

            Element LoaiKey = doc.createElement("LoaiKey");
            LoaiKey.appendChild(doc.createTextNode(ttk.getLoaiKey()));
            key.appendChild(LoaiKey);

            Element DiaChiMail = doc.createElement("DiaChiMail");
            DiaChiMail.appendChild(doc.createTextNode(ttk.getDiaChiMail()));
            key.appendChild(DiaChiMail);

            Element DuongDan = doc.createElement("DuongDan");
            DuongDan.appendChild(doc.createTextNode(ttk.getDuongDan()));
            key.appendChild(DuongDan);



            root.appendChild(key);

            // write the content into xml file


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(layDuongDanTapTin());

            transformer.transform(source, result);

//        System.out.println("File saved!");
        } catch (ParserConfigurationException | SAXException | IOException | DOMException | TransformerFactoryConfigurationError | TransformerException ex) {
        }


    }
}
